package com.hjf.ditubiaozhu.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;

import com.hjf.ditubiaozhu.R;
import com.hjf.ditubiaozhu.base.recycler.BaseSwipeAdapter;
import com.hjf.ditubiaozhu.base.recycler.OnMyRefreshListener;
import com.hjf.ditubiaozhu.base.recycler.widget.SwipeRecyclerView;
import com.hjf.ditubiaozhu.utils.LogUtils;

import java.io.IOException;
import java.util.List;

import retrofit2.adapter.rxjava.HttpException;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;


/**
 * 带有md风格的下拉刷新fragment 封装基类, 传个BaseSwipeAdapter就可以显示东西了
 *
 * @param <E>
 */
public abstract class BaseSwipeFragment<E extends BaseSwipeAdapter> extends BaseFragment {

    protected SwipeRecyclerView mMySwipeRefreshLayout;
    protected RecyclerView mRecylerView;
    protected Context mContext;
    protected BaseSwipeAdapter mRecycleAdapter;
    protected OnMyRefreshListener mOnMyRefreshListener;

    /**
     * 网络失败处理
     * 数据错误弹出msg
     */
    public static interface IFailedHandler {
        void setResult(Result result);

        void dateError();

        void connectError();

        void httpError();
    }

    public IFailedHandler iFailedHandler = new IFailedHandler() {
        Result result;

        @Override
        public void setResult(Result result) {
            this.result = result;
        }

        @Override
        public void dateError() {
            toast(result.getMsg());
        }

        @Override
        public void connectError() {
            toast("服务器正在维护");
        }

        @Override
        public void httpError() {
            toast("网络异常");
        }
    };


    /**
     * 自动加载 处理异常
     *
     * @param observable
     * @param <T>
     */
    protected <T extends Base> void autoLoad(Observable<Result<T>> observable) {
        observable.compose(this.<Result<T>>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Result<T>>() {
                    @Override
                    public void call(Result<T> result) {
                        //加载数据处理
                        if (result.getCode() == 0) {
                            List<T> beans = result.getBeans();
                            mRecycleAdapter.load((List<Base>) beans, result.getSize());
                        } else if (result.getCode() == 1001 || result.getCode() == 1002) {
                            Intent intent = new Intent();
                            //intent.setClass(mContext, LoginActivity.class);
                            mContext.startActivity(intent);
                            getActivity().finish();

                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //分析失败原因
                        if (throwable instanceof HttpException)
                            LogUtils.e("获取estate数据", "网络非200异常HttpException:", ((HttpException) throwable).code() + "");
                        if (throwable instanceof IOException) {
                            IOException exception = (IOException) throwable;
                            if (exception.getMessage().contains("connect to")) {
                                LogUtils.e("无法连接服务器", exception.getMessage());
                            } else {
                                LogUtils.e("json转换数据异常.", exception.getMessage());
                            }
                        }
                        LogUtils.e(throwable.getMessage());
                        throwable.printStackTrace();

                        mMySwipeRefreshLayout.downRefreshComplete(3);//起着停止刷新作用
                    }
                });
    }


    /**
     * 必须实现
     */
    public abstract OnMyRefreshListener getOnMyRefreshListener();

    public abstract E getBaseSwipeAdapter();

    /**
     * 获取bundle 不一定要实现
     */
    public void doBundle(Bundle bundle) {

    }

    @Override
    public int getLayoutResId() {

        return R.layout.common_swipe_recycler_fragment;
    }

    @Override
    protected void onCompletedView(Bundle savedInstanceState) {
        isInited = true; //初始化完成
        doBundle(savedInstanceState);
        lazyLoad();
    }

    @Override
    protected void lazyLoad() {
        if (!isInited || !isVisible) return;
        initData();
        isInited = false;

    }

    /**
     * 初始化数据
     */
    protected void initData() {
        mContext = getActivity();
        mOnMyRefreshListener = getOnMyRefreshListener();


        mMySwipeRefreshLayout = (SwipeRecyclerView) getView().findViewById(R.id.message_swipeRecyclerView);
        mRecylerView = mMySwipeRefreshLayout.getRecyclerView();
        mRecycleAdapter = getBaseSwipeAdapter();
        isInited = true;

        mMySwipeRefreshLayout.setAdapter(mRecycleAdapter);
        mMySwipeRefreshLayout.setOnMyRefreshListener(mOnMyRefreshListener);
        mMySwipeRefreshLayout.startDownRefresh();
    }


}
